package org.spolo.android.shape;

import org.spolo.android.nodetree.Vcanvas;
import org.spolo.android.util.ContextManager;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.RectF;

public class ImageRect extends Vcanvas {
	private Bitmap image;
	private RectF dest;
	private float factorX = 1;
	private float factorY = 1;
	private Matrix mat;

	public ImageRect(int imageId, RectF rect) {
		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inScaled = false;
		options.inPurgeable = true;
		image = BitmapFactory.decodeResource(ContextManager.getInstance()
				.getContext("Androidshow").getResources(), imageId, options);
		this.dest = rect;

		// 设置脏区为所画的区域
		this.dirty_rect = rect;
		setFactor();
	}

	@Override
	protected void drawSelfImplement(Canvas canvas) {
		super.drawSelfImplement(canvas);
		mat = canvas.getMatrix();
		canvas.drawBitmap(image, null, this.dest, null);
	}

	@Override
	public void setDirtyRect(float left, float top, float width, float hight) {
		super.setDirtyRect(dest.left + (left - dest.left) * factorX, dest.top
				+ (top - dest.top) * factorY, width * factorX, hight * factorY);
	}

	@Override
	protected boolean isChecked(float x, float y) {
		RectF rect = this.getRect();
		if (rect.contains(x, y)) {
			float[] coor = new float[] { x, y };
			Matrix temp = new Matrix(mat);
			temp.invert(temp);
			temp.mapPoints(coor);
			int ix = Math.round((coor[0] - dest.left) / factorX);
			int iy = Math.round((coor[1] - dest.top) / factorY);
			System.out.println("x:" + x + ",y:" + y);
			System.out.println("x0:" + coor[0] + ",y0:" + coor[1]);
			System.out.println("matrix:" + mat);
			System.out.println("ix:" + ix + ",iy:" + iy);
			int clr = image.getPixel(ix, iy);
			System.out.println("clr:" + clr);
			float[] center = getCenter();
			System.out
					.println("centerX:" + center[0] + ",centerY:" + center[1]);
			if (clr != 0) {
				return true;
			}
		}
		return false;
	}

	/**
	 * 设置画图区域和原图大小的比例系数
	 */
	private void setFactor() {
		float dest_width = dest.right - dest.left;
		factorX = dest_width / image.getWidth();
		float dest_hight = dest.bottom - dest.top;
		factorY = dest_hight / image.getHeight();
	}

}
